package com.seafood.repository;

import com.seafood.entity.ShoppingCart;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 购物车数据访问层
 */
@Repository
public interface ShoppingCartRepository extends JpaRepository<ShoppingCart, Long> {
    
    /**
     * 根据用户ID查找购物车所有商品
     */
    List<ShoppingCart> findByUserIdOrderByCreatedAtDesc(Long userId);
    
    /**
     * 根据用户ID和产品ID查找购物车项
     */
    Optional<ShoppingCart> findByUserIdAndProductId(Long userId, Long productId);
    
    /**
     * 检查用户购物车中是否存在指定产品
     */
    boolean existsByUserIdAndProductId(Long userId, Long productId);
    
    /**
     * 统计用户购物车商品数量
     */
    @Query("SELECT COUNT(sc) FROM ShoppingCart sc WHERE sc.user.id = :userId")
    Long countByUserId(@Param("userId") Long userId);
    
    /**
     * 计算用户购物车商品总数量
     */
    @Query("SELECT SUM(sc.quantity) FROM ShoppingCart sc WHERE sc.user.id = :userId")
    Long sumQuantityByUserId(@Param("userId") Long userId);
    
    /**
     * 删除用户购物车中的指定商品
     */
    @Modifying
    @Query("DELETE FROM ShoppingCart sc WHERE sc.user.id = :userId AND sc.product.id = :productId")
    void deleteByUserIdAndProductId(@Param("userId") Long userId, @Param("productId") Long productId);
    
    /**
     * 清空用户购物车
     */
    @Modifying
    @Query("DELETE FROM ShoppingCart sc WHERE sc.user.id = :userId")
    void deleteByUserId(@Param("userId") Long userId);
}